//
//  THTaskPublishVC.m
//  YJB
//
//  Created by YJB on 2016/12/17.
//  Copyright © 2016年 YJB. All rights reserved.
//

#import "THTaskPublishVC.h"
#import "YJGlobalHeader.h"
#import "YJNetworkTool.h"
#import "YJUserDefaultTool.h"
#import "YJTextView.h"
#import "PopoverView.h"
#import "TZImagePickerController.h"
#import "TZImageManager.h"

@interface THTaskPublishVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITableViewDataSource,TZImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *taskType;
@property (weak, nonatomic) IBOutlet UITextField *taskTitle;
@property (weak, nonatomic) IBOutlet UITextField *specialNeed;
@property (weak, nonatomic) IBOutlet UITextField *num;
@property (weak, nonatomic) IBOutlet UITextField *price;
@property (weak, nonatomic) IBOutlet UITextField *totalMoney;
@property (weak, nonatomic) IBOutlet YJTextView *taskDescription;
@property (weak, nonatomic) IBOutlet UIButton *publishBtn;
@property (weak, nonatomic) IBOutlet UIView *containView;

@property(nonatomic,strong)NSMutableArray *selectedPhotos;
@property(nonatomic,strong)NSMutableArray *selectedAssets;


@end

@implementation THTaskPublishVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _selectedPhotos = [NSMutableArray array];
    _selectedAssets = [NSMutableArray array];
    
    self.navigationItem.title = @"发布任务";
    NSArray *textFields = @[_taskType,_taskTitle,_specialNeed,_num,_price,_totalMoney];
    self.publishBtn.enabled = YES;
    self.taskDescription.placeholder = @"请输入任务描述";
    for (int i = 0; i < textFields.count; i ++)
    {
        UIView *leftView = [[UIView alloc]init];
        leftView.width = 12;
        UITextField *textField = textFields[i];
        textField.leftView = leftView;
        textField.leftViewMode = UITextFieldViewModeAlways;
    }
    
    //rac部分
    RAC(self.totalMoney,text) = [[RACSignal combineLatest:@[_price.rac_textSignal,_num.rac_textSignal] reduce:^id(NSString *price,NSString *total){
        return [@(price.doubleValue * total.doubleValue) stringValue ];
    }] skip:1];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
    @weakify(self);
    [tap.rac_gestureSignal subscribeNext:^(id x) {
        @strongify(self);
        [self.view endEditing:YES];
//        self.popView.hidden = YES;
    }];
     [_containView addGestureRecognizer:tap];
}


- (NSMutableArray *)showActions:(NSArray *)titles {
    NSMutableArray *actions = [[NSMutableArray alloc] init];
    
    for (NSString *title in titles) {
        PopoverAction *action = [PopoverAction actionWithImage:[UIImage imageNamed:@"right_menu_multichat"] title:title handler:^(PopoverAction *action) {

            if (titles.count == 5) {
                self.taskType.text = action.title;
            }else{
                self.specialNeed.text = action.title;
            }
#pragma mark - 该Block不会导致内存泄露, Block内代码无需刻意去设置弱引用.
        }];
        [actions addObject: action];
    }
    return actions;
}


- (IBAction)changeTaskType:(UIButton *)button
{
    NSArray *array = [[NSArray alloc] initWithObjects:@"注册",@"下载",@"试玩",@"投票",@"其他", nil];
    PopoverView *popoverView = [PopoverView popoverView];
    [popoverView showToView:button withActions:[self showActions:array]];
}
- (IBAction)changeSpecialNeed:(UIButton *)button
{
    NSArray *array = [[NSArray alloc] initWithObjects:@"截图",@"收短信",@"特定资料",@"其他", nil];
    PopoverView *popoverView = [PopoverView popoverView];
    [popoverView showToView:button withActions:[self showActions:array]];
}
- (IBAction)uploadImageBtnClick:(UIButton *)button
{
    
    [self presentImagePickVC];
    
    
    
}

#pragma mark ----------------------- 图片选择器的代理方法
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos
{
    self.selectedPhotos = [photos mutableCopy];
    self.selectedAssets = [assets mutableCopy];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"])
    {
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
        tzImagePickerVc.sortAscendingByModificationDate = YES;
        [tzImagePickerVc showProgressHUD];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image completion:^{
            [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES completion:^(TZAlbumModel *model) {
                [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                    [tzImagePickerVc hideProgressHUD];
                    TZAssetModel *assetModel = [models firstObject];
                    if (tzImagePickerVc.sortAscendingByModificationDate) {
                        assetModel = [models lastObject];
                    }
                    [self.selectedAssets addObject:assetModel.asset];
                    [self.selectedPhotos addObject:image];
                    
                    //                    [image imageByScaledToSize:CGSizeMake(300, 300)];
//                    [self.submitImages addObject:image];
//                    for (int i = 0; i<=self.submitImages.count; i++) {
//                        UIButton *button = [self.scrollView viewWithTag:i+2];
//                        button.hidden = NO;
//                        if (i < self.submitImages.count) {
//                            [button setBackgroundImage:self.submitImages[i] forState:UIControlStateNormal];
//                        }
//                    }
                }];
            }];
        }];
    }
}




- (void)presentImagePickVC
{
    TZImagePickerController *imagePickerVC = [[TZImagePickerController alloc]initWithMaxImagesCount:9 delegate:self];
    imagePickerVC.selectedAssets = self.selectedAssets;
    //导航栏颜色
    imagePickerVC.navigationBar.tintColor = WHITECOLOR;
    imagePickerVC.navigationBgImage = @"nav_backGround";
    //不要拍照按钮
    imagePickerVC.allowTakePicture = NO;
    //不能选择视频
    imagePickerVC.allowPickingVideo = NO;
    //不允许选择原图
    imagePickerVC.allowPickingOriginalPhoto = NO;
    imagePickerVC.maxImagesCount = 4;
    [self presentViewController:imagePickerVC animated:YES completion:nil];
}

- (IBAction)changeProtocol:(UIButton *)button
{
    
}

- (IBAction)publishBtnClick:(UIButton *)button
{
    [self.view endEditing:YES];
    NSArray *messages = @[@"请输入任务标题",@"请输入任务个数",@"请输入单价"];
    NSArray *textFields = @[_taskTitle,_num,_price];
    for (int i = 0; i < messages.count ; i ++)
    {
        UITextField *textField = textFields[i];
        if (textField.text.length == 0)
        {
            [MBProgressHUD showError:messages[i]];
            return;
        }
    }
    if (!_taskDescription.hasText)
       [MBProgressHUD showError:@"请输入任务描述"];
    
    //获取{"action":"set_task_add","makegold":{"username":"用户名","class":"任务类型","title":"标题","need":"特定需求","content":"任务描述","num":"名额个数","price":"单价","img_list":(可选)[{"img_url":"localhost/makegold/pdoconn/uploads/1467260562.jpeg"},{"img_url":"localhost/makegold/pdoconn/uploads/1467256954.jpg"}],"user_info":"用户信息","phone_info":"手机信息","md5_key":"密钥"}}
    [MBProgressHUD showMessage:@""];
    NSString *strTest = [[@"admin"stringByAppendingString:@"iOS"]stringByAppendingString:appMd5Key];
    NSString *keyStr = [strTest md5];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"action"] = @"set_task_add";
    params[@"makegold"] = @{@"username":[YJUserDefaultTool readUserName],
                            @"class":_taskType.text,
                            @"title":_taskTitle.text,
                            @"need":_specialNeed.text,
                            @"content":_taskDescription.text,
                            @"price":_price.text,
                            @"num":_num.text,
                            @"img_list":@"",
                            @"user_info":@"admin",
                            @"phone_info":@"iOS",
                            @"md5_key":keyStr,
                            };
    
    [YJNetworkTool postWithUrl:THURL(@"task.php") parameters:params success:^(id responseObject) {
        [MBProgressHUD hideHUD];
        if ([responseObject[@"return"][@"code"] integerValue] == 200)
        {
            [MBProgressHUD showSuccess:@"发布成功"];
//            [NOTIFICATIONCENTER postNotificationName:THUserDidPublishCpcTaskNotification object:nil userInfo:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }else
        {
            NSString *message = responseObject[@"return"][@"message"];
            [MBProgressHUD showError:message toView:self.view];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络不佳,稍后重试" toView:self.view];
    }];
}

- (IBAction)cancelBtnClick:(UIButton *)button {
}

@end
